from fastapi import APIRouter, Depends, HTTPException, status, Request, Response, Form
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
from sqlalchemy.orm import Session
from app.database.database import get_db
from app.utils.auth import verify_password, create_access_token, get_password_hash, get_user_by_name, ACCESS_TOKEN_EXPIRE_MINUTES, get_current_active_user
from app.models.models import SysUser
from app.schemas.schemas import Token, UserCreate, UserResponse
from datetime import timedelta
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from typing import Optional

router = APIRouter()
templates = Jinja2Templates(directory="app/templates")

# 页面路由 - 返回HTML页面
@router.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
    return templates.TemplateResponse("login.html", {"request": request})

@router.get("/register", response_class=HTMLResponse)
async def register_page(request: Request):
    return templates.TemplateResponse("register.html", {"request": request})

# API路由 - 返回JSON数据
@router.post("/api/login", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 检查用户是否激活
    if user.is_active == 0:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="用户未激活",
        )
    
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.name}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

@router.post("/api/register", response_model=UserResponse)
def register_user(user: UserCreate, db: Session = Depends(get_db)):
    db_user = get_user_by_name(db, name=user.name)
    if db_user:
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    hashed_password = get_password_hash(user.password)
    db_user = SysUser(
        name=user.name,
        email=user.email,
        password=hashed_password,
        remark=user.remark,
        is_admin=0,  # 默认非管理员
        is_active=0,  # 默认未激活
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


# 认证用户
def authenticate_user(db: Session, username: str, password: str):
    user = get_user_by_name(db, name=username)
    if not user or not verify_password(password, user.password):
        return None
    return user 